package com.itheima.reggie.controlller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.impl.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.LocalTime;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     *
     * @param request  登录成功后 id存入 session中
     * @param employee 传入的是json  要用requestbody
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

     // 1、将页面提交的密码 password 进行 md5 加密处理
     String password=employee.getPassword();
     password=DigestUtils.md5DigestAsHex(password.getBytes());//明文密码处理

     //2、根据页面提交的用户名 username 查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
     //3、如果没有查询到则返回登录失败结果
        if(emp==null){
            return R.error("登录失败");
        }
     //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");

        }
     //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus()==0){
            return R.error("用户已禁用");
        }
     //6、登录成功，将员工 id 存入 Session 并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }


    /**
     * 员工退出
     * 清理session当前保存的id 用request请求即可
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("员工信息 :{}",employee);
        //设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));//员工信息 :Employee(id=null, username=asdas, name=张三, password=null, phone=17865655656, sex=1, idNumber=111222333444555666, status=null, createTime=null, updateTime=null, createUser=null, updateUser=null)

        //设置当前创建时间
        //employee.setCreateTime(LocalDateTime.now());
        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录的用户 id 以便添加 添加员工的当事人id
        //Long empId = (Long)request.getSession().getAttribute("employee");

        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);

        employeeService.save(employee); //因为EmployeeService接口继承了mybatis的IService接口  里面有save方法
        return R.success("添加成功");
    }

    /**
     * 员工分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={} ,pageSize={},name={}",page,pageSize,name);
        
        //构造分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件  name 不为空时  第二个参数 是告诉哪一个实体类的哪个属性 第三个 是真实比较的值
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加一个排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询

        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);

    }


    /**
     * 启用与禁用
     * @param employee
     * @return
     */
    @PutMapping()
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee) {

        log.info(employee.toString());

        long id = Thread.currentThread().getId();
        log.info("当前的线程Id为,{}",id);

        //设置当前的修改时间
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**
     * 编辑员工信息时 回显页面 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getByid(@PathVariable Long id){
        log.info("getByid:{}",id);
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
